import 'package:erp/Entity/Supplier.dart';
import 'package:erp/Entity/SupplierType.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/Store/SupplierStore.dart';
import 'package:erp/UI/Components/EmbeddableStatefulWidget.dart';
import 'package:erp/UI/Components/EventfulState.dart';
import 'package:erp/UI/Components/ListDividerGenerator.dart';
import 'package:erp/UI/Components/LogoScaffold.dart';
import 'package:erp/UI/Components/MessageDialog.dart';
import 'package:erp/UI/Components/QuestionDialog.dart';
import 'package:erp/UI/Pages/BasicInformationManagementPages/SupplierTypePages/SupplierTypePage.dart';
import 'package:erp/global.dart';
import "package:flutter/material.dart";

class SupplierInformationPage extends StatelessWidget {
  bool selectionMode;
  String title;

  SupplierInformationPage({this.selectionMode = false, this.title = "مال تەمىنلىگۈچىلەر"});

  @override
  Widget build(BuildContext context) {
    return SupplierInformationPageStateful(this);
  }
}

class SupplierInformationPageStateful extends StatefulWidget {

  SupplierInformationPage parameter;

  SupplierInformationPageStateful(this.parameter);

  @override
  State<StatefulWidget> createState() => SupplierInformationPageState(parameter);
}

class SupplierInformationPageState extends EventfulState<SupplierInformationPageStateful> {
  SupplierInformationPage parameter;

  SupplierInformationPageState(this.parameter);
  @override
  void initState() {
    eventIds = [
      bus.subscribe(Events.SUPPLIER_INSERT_SUCCESS, (bus, data){setState(() {});}),
      bus.subscribe(Events.SUPPLIER_SELECT_SUCCESS, (bus, data){setState(() {});}),
      bus.subscribe(Events.SUPPLIER_UPDATE_SUCCESS, (bus, data){setState(() {});}),
      bus.subscribe(Events.SUPPLIER_DELETE_SUCCESS, (bus, data){setState(() {});}),

      bus.subscribe(Events.SUPPLIER_INSERT_ERROR, (bus, error){
        showMessageDialog(context, title: "قوشۇش مەغلۇپ بولدى", content: error.toString());
      }),
      bus.subscribe(Events.SUPPLIER_UPDATE_ERROR, (bus, error){
        showMessageDialog(context, title: "يىڭىلاش مەغلۇپ بولدى", content: error.toString());
      }),
      bus.subscribe(Events.SUPPLIER_DELETE_ERROR, (bus, error){
        showMessageDialog(context, title: "ئۆچۈرۈش مەغلۇپ بولدى", content: error.toString());
      }),

    ];
    super.initState();
  }
  @override
  Widget build(BuildContext context) {

    return LogoScaffold(
      floatingActionButton: FloatingActionButton(
          onPressed: () async {
            var supplier = Supplier();
            var result = await showSupplierEditDialog(context, supplier) ?? false;
            if (result) bus.publish(Events.SUPPLIER_INSERT_REQUEST, supplier);
          },
        child: Icon(Icons.add),
      ),
      title: parameter.title,
      assetsLogoName: "assets/pictures/purchases.png",
      heroName: "SupplierInformationPageImage",
      contentDelegate: SliverChildListDelegate(ListDividerGenerator(SupplierStore.suppliers.map((item) => buildItem(item)).toList(), Divider()).items),
      useSearchBar: true,
    );
  }

  Widget buildItem(Supplier data){
    return ListTile(
      leading: Image.asset("assets/pictures/purchases.png", width: 48.0, height: 48.0,),
      title: Text(data.name),
      subtitle: Text(data.phone),
      trailing: SizedBox(
        width: 100.0,
        child: Row(
//          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            IconButton(icon: Icon(Icons.edit), onPressed: () async {
              var supplier = data.clone();
              var result = await showSupplierEditDialog(context, supplier) ?? false;
              if (result){
                bus.publish(Events.SUPPLIER_UPDATE_REQUEST, supplier);
              }
            }),
            IconButton(icon: Icon(Icons.delete), onPressed: () async {
              var result = await showQuestionDialog(context, title: "ئەسكەرتىش", content: "راستىنلا ئۆچۈرەمسىز؟") ?? false;
              if (result) {
                bus.publish(Events.SUPPLIER_DELETE_REQUEST, data);
              }
            }),
          ],
        ),
      ),
      onTap: (){
        if (parameter.selectionMode){
          Navigator.of(context).pop(data);
        }
      },
    );
  }

  Future<bool> showSupplierEditDialog(BuildContext context, Supplier data) async {

    var nameTextController = TextEditingController(text:  data.name);
    var phoneTextController = TextEditingController(text:  data.phone);

    return showDialog(context: context, builder: (context) => Directionality(textDirection: TextDirection.rtl, child: AlertDialog(
      title: Text("تەمىنلىگۈچى ئۇچۇرىنى تەھرىرلەڭ"),
      content: EmbeddedWidget(widgetBuilder: (context, widget){
        return Wrap(
          direction: Axis.horizontal,
          children: <Widget>[
            TextField(
              controller: nameTextController,
              decoration: InputDecoration(
                  labelText: "ئىسمى",
                  hintText: "مال تەمىنلىگۈچى ئىسمى"
              ),
              onChanged: (text) => data.name = text,
            ),
            TextField(
              controller: phoneTextController,
              decoration: InputDecoration(
                labelText: "تېلېفون نومۇرى",
                hintText: "تەمىنلىگۈچى ئىسمى",
              ),
              keyboardType: TextInputType.numberWithOptions(signed: true, decimal: false),
              onChanged: (text) => data.phone = text,
            ),
            SizedBox(
              height: 20.0,
              width: 20.0,
            ),
            Row(
              children: <Widget>[
                Expanded(
                  child: Text("تەمىنلىگۈچى تىپىنى تاللاڭ"),
                ),
                RaisedButton(
                    child: Text(data.typeName ?? "تۈر تاللاڭ"),
                    onPressed: () async {
                      var result = await Navigator.of(context).push<SupplierType>(MaterialPageRoute(builder: (context) => SupplierTypePage(selectionMode: true,)));
                      if (result != null){
                        data.type = result.id;
                        widget.setState((){});
                        data.typeName = result.name;
                      }
                    }
                )
              ],
            )
          ],
        );
      }),
      actions: <Widget>[
        FlatButton(onPressed: (){
          Navigator.of(context).pop(false);
        }, child: Text("بىكار قىلىش")),
        FlatButton(onPressed: (){

          Navigator.of(context).pop(true);
        }, child: Text("جەزىملەشتۈرۈش")),
      ],
    )), barrierDismissible: false);
  }
}